package edu.eas.auth.component;

import edu.eas.auth.domain.SecurityUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * JWT内容增强器
 *
 * @author cql
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {

    /**
     * 结合score做细粒度的权限控制:
     * https://blog.csdn.net/qq_43437874/article/details/121552989
     *
     * @param accessToken
     * @param authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

        // 如果scope中有数据,说明是外部系统授权登录,则需要将原来的权限角色进行情况,设置为scope中的权限角色
        Set<String> scope = accessToken.getScope();
        if (!scope.isEmpty()) {
            Collection authorities = securityUser.getAuthorities();
            // 清空原本的角色
            authorities.clear();
            // 加入 scope 中的角色
            scope.forEach(item -> authorities.add(new SimpleGrantedAuthority(item)));
        }

        Map<String, Object> info = new HashMap<>();
        // 把用户ID设置到JWT中
        info.put("id", securityUser.getId());
        info.put("client_id", securityUser.getClientId());
        info.put("user_type", securityUser.getUserType());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}